package com.http;

import cn.hutool.aop.ProxyUtil;
import cn.hutool.http.HttpUtil;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * @author xurongbei
 */
public class HttpRequestUtil {

    public static String post(String path,String proxyIp,int proxyPort) throws IOException {
        URL url = null;
        HttpURLConnection conn = null;
        DataOutputStream out = null;
        BufferedReader in = null;
        try {
            url = new URL(path);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, proxyPort));
            conn = (HttpURLConnection) url.openConnection(proxy);
            // 提交模式
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "text/xml");
            //conn.setRequestProperty("Content-Type", "application/json");
            // 连接超时 单位毫秒
            conn.setConnectTimeout(20000);
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            out = new DataOutputStream(conn.getOutputStream());
            out.flush();

            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), Charset.forName("UTF-8")));
            final StringBuilder buffer = new StringBuilder(256);

            String line;

            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
            return buffer.toString();
        } catch (final IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        String proxyIp = "1.203.111.243";
        proxyIp = "localhost";
        int proxyPort = 9104;
        proxyPort = 8000;
        String result = post("http://192.168.137.113:80/test",proxyIp,proxyPort);
        System.out.println(result);

    }
}
